import React, { useEffect, useState } from "react";
import {
  CheckCircleOutlined,
  CloseCircleOutlined,
  ExclamationCircleOutlined,
  InfoCircleOutlined,
  CloseOutlined,
} from "@ant-design/icons";
import "./CustomMessage.scss";

export interface MessageProps {
  type: "success" | "error" | "warning" | "info";
  content: string;
  duration?: number; // 自动关闭时间，单位毫秒，0表示不自动关闭
  onClose?: () => void;
}

const CustomMessage: React.FC<MessageProps> = ({
  type,
  content,
  duration = 3000,
  onClose,
}) => {
  const [visible, setVisible] = useState(true);

  useEffect(() => {
    if (duration > 0) {
      const timer = setTimeout(() => {
        setVisible(false);
        onClose?.();
      }, duration);
      return () => clearTimeout(timer);
    }
  }, [duration, onClose]);

  const handleClose = () => {
    setVisible(false);
    onClose?.();
  };

  if (!visible) return null;

  const getIcon = () => {
    switch (type) {
      case "success":
        return <CheckCircleOutlined className="message-icon success" />;
      case "error":
        return <CloseCircleOutlined className="message-icon error" />;
      case "warning":
        return <ExclamationCircleOutlined className="message-icon warning" />;
      case "info":
        return <InfoCircleOutlined className="message-icon info" />;
      default:
        return <InfoCircleOutlined className="message-icon info" />;
    }
  };

  return (
    <div className={`custom-message ${type}`}>
      {getIcon()}
      <span className="message-content">{content}</span>
      <CloseOutlined className="message-close" onClick={handleClose} />
    </div>
  );
};

export default CustomMessage;
